//
//  MILSenceModeViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/15.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILSenceModeViewController.h"
#import "MILSenceModeTableViewCell.h"
#import "MILSenceSettingViewController.h"
#import "GetSenceListApi.h"
#import "DeleteSenceApi.h"
#import "RunSenceApi.h"
#import "MILSenceModel.h"

@interface MILSenceModeViewController ()<MILSenceModeDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property(nonatomic,strong)NSMutableArray *myDataMutableArray;

@end

@implementation MILSenceModeViewController
#pragma mark -- 懒加载
- (NSMutableArray *)myDataMutableArray
{
    if (!_myDataMutableArray)
    {
        _myDataMutableArray = [NSMutableArray array];
    }
    
    return _myDataMutableArray;
}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"情景模式"];
    self.navigationBar.backgroundColor = [UIColor blackColor];
    [self setLeftButtonImage:[UIImage imageNamed:@"back_icon"]];
    
}

#pragma mark -- UI
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILSenceModeView];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //获取场景
    [self getSenceList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//初始化UI
- (void)initMILSenceModeView
{
    [self.myTableView registerNib:[UINib nibWithNibName:@"MILSenceModeTableViewCell" bundle:nil] forCellReuseIdentifier:@"MILSenceModeTableViewCell"];
}


#pragma mark -- 获取场景
- (void)getSenceList
{
    GetSenceListApi *api = [[GetSenceListApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"device_id":self.deviceModel.device_id}];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        if ([myDic[@"errcode"] intValue] == 0) {
            [self.myDataMutableArray removeAllObjects];
            NSArray *returnDataArray = myDic[@"data"];
            for (NSDictionary *dic in returnDataArray) {
                MILSenceModel *model = [[MILSenceModel alloc]init];
                model.ID = dic[@"id"];
                model.name = dic[@"name"];
                model.r = dic[@"r"];
                model.g = dic[@"g"];
                model.b = dic[@"b"];
                model.brightness = dic[@"brightness"];
                model.colour_temperature = dic[@"colour_temperature"];
                model.ctime = dic[@"ctime"];
                model.twinkle = dic[@"twinkle"];
                model.selected = NO;
                [self.myDataMutableArray addObject:model];
            }

            [self.myTableView reloadData];

        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }
        
        
    } failure:^(YTKBaseRequest *request) {
        
        [SVProgressHUD showErrorWithStatus:@"请求失败"];
    }];

}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.myDataMutableArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MILSenceModeTableViewCell  *Cell=[tableView  dequeueReusableCellWithIdentifier:@"MILSenceModeTableViewCell"];
    MILSenceModel *senceModel = self.myDataMutableArray[indexPath.row];

    if (senceModel.selected)
    {
        Cell.senceStatusImageView.image = [UIImage imageNamed:@"xuanzhong"];
    } else {
        Cell.senceStatusImageView.image = [UIImage imageNamed:@"check_box"];
    }
    Cell.myDeviceNameLabel.text = self.deviceModel.name;
    [Cell.senceIconBtn setBackgroundImage:[UIImage imageNamed:@"mode_rest"] forState:UIControlStateNormal];
    Cell.senceModel = senceModel;
    Cell.delegate = self;
    
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MILSenceSettingViewController *milSenceSettingVC = [[MILSenceSettingViewController alloc]init];
    MILSenceModel *model = self.myDataMutableArray[indexPath.row];
    milSenceSettingVC.senceModel = model;
    milSenceSettingVC.deviceID = self.deviceModel.device_id;
    milSenceSettingVC.senceID = [model.ID intValue];
    milSenceSettingVC.run = model.selected;
    [self.navigationController pushViewController:milSenceSettingVC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return   1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 70;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 70)];
    
    UIButton *guideBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 20, SCREEN_WIDTH-30, 50)];
    [guideBtn setTitle:@"+添加" forState:UIControlStateNormal];
    [guideBtn setBackgroundImage:[UIImage imageNamed:@"tianjiakuang"] forState:UIControlStateNormal];
    [guideBtn addTarget:self action:@selector(addSenceClickAction) forControlEvents:UIControlEventTouchUpInside];
    
    [myView addSubview:guideBtn];
    
    return myView;
}


#pragma mark -- MILSenceModeDelegate
- (void)milRunSenceModeButtonClick:(UIButton *)btn
{
    MILSenceModeTableViewCell * cell = nil;
    if ([btn isKindOfClass:[UIButton class]])
    {
        cell = (MILSenceModeTableViewCell *)[[btn superview]superview];
    }
    
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    MILSenceModel *model = self.myDataMutableArray[indexPath.row];
    if (model)
    {
        RunSenceApi *api = [[RunSenceApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"id":model.ID}];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSDictionary * myDic = [request responseJSONObject];
            if ([myDic[@"errcode"] intValue] == 0) {
                
                [SVProgressHUD showSuccessWithStatus:@"运行场景成功"];
                for (int i = 0; i < self.myDataMutableArray.count; i++) {
                    MILSenceModel *senceModel = self.myDataMutableArray[i];
                    if (i == indexPath.row) {
                        senceModel.selected = YES;
                    } else {
                        senceModel.selected = NO;
                    }
                }
                [self.myTableView reloadData];
//                cell.senceStatusImageView.image = [UIImage imageNamed:@"xuanzhong"];
            }else{
                [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
            }
            
            
        } failure:^(YTKBaseRequest *request) {
            
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
        }];
        
    }
}

- (void)milDeleteSenceModeButtonClick:(UIButton *)btn
{
    MILSenceModeTableViewCell * cell = nil;
    if ([btn isKindOfClass:[UIButton class]])
    {
        cell = (MILSenceModeTableViewCell *)[[btn superview]superview];
    }
    
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    MILSenceModel *model = self.myDataMutableArray[indexPath.row];
    if (model)
    {
        [[AlertViewManager shareManager]initWithMessage:@"是否确认删除该场景？" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确认"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
            if (buttonIndex == 1) {
                DeleteSenceApi *api = [[DeleteSenceApi alloc]initWithDictionary:@{@"uid":EXRACT_OBJECT(UID),@"token":EXRACT_OBJECT(TOKEN),@"id":model.ID}];
                [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
                    NSDictionary * myDic = [request responseJSONObject];
                    if ([myDic[@"errcode"] intValue] == 0) {
                        
                        [SVProgressHUD showSuccessWithStatus:@"删除场景成功"];
                        [self getSenceList];
                    }else{
                        [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
                    }
                    
                    
                } failure:^(YTKBaseRequest *request) {
                    
                    [SVProgressHUD showErrorWithStatus:@"请求失败"];
                }];

            }
        }];
        
    }
}

#pragma mark -- 按钮点击事件
//添加情景
- (void)addSenceClickAction
{
    MILSenceSettingViewController *milSenceSettingVC = [[MILSenceSettingViewController alloc]init];
    milSenceSettingVC.deviceID = self.deviceModel.device_id;
    milSenceSettingVC.senceModel = [[MILSenceModel alloc] init];
    milSenceSettingVC.senceID = 0;
    [self.navigationController pushViewController:milSenceSettingVC animated:YES];
}


@end
